<?php
namespace app\backend\controller;

class RecycleRegion extends Backend {
	
	/**
	 * 首页
	 */
	public function index() {
		
		$view = \think\View::instance();
		$request = \think\Request::instance();
		
		$where = array();
		$condition = array();
		$condition['title'] = $request->get('title', '');
		if(0 < mb_strlen($condition['title'], 'utf8')){
			$where['region.name_full'] = array('like', '%%'.$condition['title'].'%%');
		};
		$condition['is_recovery'] = $request->get('is_recovery', '');
		if((0 < mb_strlen($condition['is_recovery'], 'utf8')) && settype($condition['is_recovery'], 'integer')){
			$where['region.is_recovery'] = $condition['is_recovery'];
		};
		$view->assign('condition', $condition);
		
		$field = array(
			'`region`.`id`', '`region`.`name_full`', '`region`.`is_recovery`',
			'(SELECT COUNT(`recycle_order`.`id`) FROM `recycle_order` WHERE `recycle_order`.`region_district` = `region`.`id`) AS `order_number`',
		);
		$region_select = \app\common\model\RegionModel::field($field)
			->where('grade', 3)
			->where($where)
			->order('order_number DESC')
			->paginate(10, false, array('query'=>$condition));
		$view->assign('page', $region_select->render());
		
		$region_list = array();
		foreach($region_select as $RecycleCargoModel){
			$region = $RecycleCargoModel->toArray();
			$region['is_recovery_string'] = $RecycleCargoModel->getIsRecoveryString();
			$region_list[] = $region;
		};
		$view->assign('data_list', $region_list);
		
		$is_recovery = \app\common\model\RegionModel::$is_recovery;
		$view->assign('is_recovery', $is_recovery);
		
		unset($where, $condition, $field, $region_select, $RecycleCargoModel);
		return $view->fetch();
		
	}
	  

	/**
	 * 修改状态
	 */
	public function change_recovery() {
		
		$parameter = \think\Request::instance()->post();
		$judge_1 = array_key_exists('id', $parameter) && is_integer($parameter['id']) && (0 < $parameter['id']);
		$judge_2 = array_key_exists('status', $parameter) && is_integer($parameter['status']) && in_array($parameter['status'], array(0, 1));
		if(!$judge_1 || !$judge_2){
			return $this->disposeJson(1, '参数校验失败');
		};
		
		$RegionModel = \app\common\model\RegionModel::get($parameter['id']);
		if(null === $RegionModel){
			return $this->disposeJson(1, '目标未找到，请刷新后重试');
		}else if($RegionModel->is_recovery !== $parameter['status']){
			return $this->disposeJson(1, '目标状态已改变，请刷新后重试');
		};
		
		$RegionModel->is_recovery = (0 === $parameter['status']) ? 1 : 0;
		$result = $RegionModel->save();
		if(false == $result){
			return $this->disposeJson(1, '操作失败，请刷新后重试');
		};
		
		return $this->disposeJson(0, '操作成功，即将刷新');
		
	}
	
}